//
//  AFNTools.m
//  TongCan-Admin
//
//  Created by 刘金达 on 16/2/22.
//  Copyright © 2016年 LJD. All rights reserved.
//

#import "AFNTools.h"

@implementation AFNTools

#pragma mark - GET
+ (void)getWithUrl:(NSString *)url andParameters:(NSDictionary *)parameter andSuccessBlock:(sucessBlock)success andFaileBlock:(faileBlock)faile
{
    
    NSString *uid = [[NSUserDefaults standardUserDefaults] objectForKey:@"uid"];
    NSString *mcode = [[NSUserDefaults standardUserDefaults] objectForKey:@"mcode"];
    if (uid && mcode) {
        
        [parameter setValue:uid forKey:@"uid"];
        [parameter setValue:mcode forKey:@"mcode"];
    }
    
    // 1.创建管理者
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    // 2.发送请求
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    // 设置超时时间
    [manager.requestSerializer willChangeValueForKey:@"timeoutInterval"];
    manager.requestSerializer.timeoutInterval = 10.f;
    [manager.requestSerializer didChangeValueForKey:@"timeoutInterval"];
    
    
    // https 请求
    AFSecurityPolicy *securt = [AFSecurityPolicy defaultPolicy];
    securt.allowInvalidCertificates = YES;
    manager.securityPolicy = securt;
    
    
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html", nil];
    
    [manager GET:url parameters:parameter progress:^(NSProgress * _Nonnull downloadProgress) {
        
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        if (success) {
            if ([[responseObject objectForKey:@"code"] integerValue] == 200) {
                
                success([responseObject objectForKey:@"data"]);
            } else {
                
                NSError *error = [NSError errorWithDomain:@"服务器错误" code:[[responseObject objectForKey:@"code"] integerValue] userInfo:nil];
                faile(error);
            }
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        if (faile) {
            faile(error);
        }
    }];
    
}



#pragma mark - POST
+ (void)postWithUrl:(NSString *)url andParameters:(NSMutableDictionary *)parameter andSuccessBlock:(sucessBlock)success andFaileBlock:(faileBlock)faile
{
    
    NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithDictionary:parameter];
    
    NSString *uid = [[NSUserDefaults standardUserDefaults] objectForKey:@"uid"];
    NSString *mcode = [[NSUserDefaults standardUserDefaults] objectForKey:@"mcode"];
    if (uid && mcode) {
        
        [dic setValue:uid forKey:@"uid"];
        [dic setValue:mcode forKey:@"mcode"];
    }
    
    // 1.创建管理者
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    // 2.发送请求
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    // 设置超时时间
    [manager.requestSerializer willChangeValueForKey:@"timeoutInterval"];
    manager.requestSerializer.timeoutInterval = 10.f;
    [manager.requestSerializer didChangeValueForKey:@"timeoutInterval"];
    
    
    // https 请求
    AFSecurityPolicy *securt = [AFSecurityPolicy defaultPolicy];
    securt.allowInvalidCertificates = YES;
    manager.securityPolicy = securt;
    
    
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html", nil];
    [manager POST:url parameters:dic progress:^(NSProgress * _Nonnull uploadProgress) {
        
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        if (success) {

            success(responseObject);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        if (faile) {
            faile(error);
        }
    }];
 
}

//+(void)GET:(NSString *)url params:(NSDictionary *)params
//   success:(LHResponseSuccess)success fail:(LHResponseFail)fail{
//    
//    AFHTTPSessionManager *manager = [AFNTools managerWithBaseURL:nil sessionConfiguration:NO];
//    [manager GET:url parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//        
//        id dic = [AFNTools responseConfiguration:responseObject];
//        
//        success(task,dic);
//    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//        fail(task,error);
//    }];
//}
//
//+(void)GET:(NSString *)url baseURL:(NSString *)baseUrl params:(NSDictionary *)params
//   success:(LHResponseSuccess)success fail:(LHResponseFail)fail{
//    
//    AFHTTPSessionManager *manager = [AFNTools managerWithBaseURL:baseUrl sessionConfiguration:NO];
//    [manager GET:url parameters:params progress:^(NSProgress * _Nonnull downloadProgress) {
//        
//    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//        
//        
//        id dic = [AFNTools responseConfiguration:responseObject];
//        
//        success(task,dic);
//    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//        fail(task,error);
//    }];
//    
//}
//
//+(void)POST:(NSString *)url params:(NSDictionary *)params
//    success:(LHResponseSuccess)success fail:(LHResponseFail)fail{
//    
//    NSString *uid = [[NSUserDefaults standardUserDefaults] objectForKey:@"uid"];
//    NSString *mcode = [[NSUserDefaults standardUserDefaults] objectForKey:@"mcode"];
//    if (uid && mcode) {
//        
//        [params setValue:uid forKey:@"uid"];
//        [params setValue:mcode forKey:@"mcode"];
//    }
//    
//    AFHTTPSessionManager *manager = [AFNTools managerWithBaseURL:nil sessionConfiguration:NO];
//    
//    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html", nil];
//    
//    [manager POST:url parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//        
//        id dic = [AFNTools responseConfiguration:responseObject];
//        
//        success(task,dic);
//    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//        fail(task,error);
//    }];
//}
//
//+(void)POST:(NSString *)url baseURL:(NSString *)baseUrl params:(NSDictionary *)params
//    success:(LHResponseSuccess)success fail:(LHResponseFail)fail{
//    
//    AFHTTPSessionManager *manager = [AFNTools managerWithBaseURL:baseUrl sessionConfiguration:NO];
//    [manager POST:url parameters:params progress:^(NSProgress * _Nonnull uploadProgress) {
//        
//    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//        
//        id dic = [AFNTools responseConfiguration:responseObject];
//        
//        success(task,dic);
//    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//        fail(task,error);
//    }];
//}
//
//+(void)uploadWithURL:(NSString *)url params:(NSDictionary *)params fileData:(NSData *)filedata name:(NSString *)name fileName:(NSString *)filename mimeType:(NSString *) mimeType progress:(LHProgress)progress success:(LHResponseSuccess)success fail:(LHResponseFail)fail{
//    
//    AFHTTPSessionManager *manager = [AFNTools managerWithBaseURL:nil sessionConfiguration:NO];
//    
//    [manager POST:url parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
//        
//        [formData appendPartWithFileData:filedata name:name fileName:filename mimeType:mimeType];
//        
//    } progress:^(NSProgress * _Nonnull uploadProgress) {
//        
//        progress(uploadProgress);
//        
//    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//        
//        id dic = [AFNTools responseConfiguration:responseObject];
//        success(task,dic);
//        
//    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//        fail(task,error);
//    }];
//}
//
//+(void)uploadWithURL:(NSString *)url
//             baseURL:(NSString *)baseurl
//              params:(NSDictionary *)params
//            fileData:(NSData *)filedata
//                name:(NSString *)name
//            fileName:(NSString *)filename
//            mimeType:(NSString *) mimeType
//            progress:(LHProgress)progress
//             success:(LHResponseSuccess)success
//                fail:(LHResponseFail)fail{
//    
//    AFHTTPSessionManager *manager = [AFNTools managerWithBaseURL:baseurl sessionConfiguration:YES];
//    
//    [manager POST:url parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
//        [formData appendPartWithFileData:filedata name:name fileName:filename mimeType:mimeType];
//    } progress:^(NSProgress * _Nonnull uploadProgress) {
//        progress(uploadProgress);
//    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//        
//        id dic = [AFNTools responseConfiguration:responseObject];
//        
//        success(task,dic);
//        
//        
//        success(task,responseObject);
//    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//        fail(task,error);
//    }];
//}
//
//+(NSURLSessionDownloadTask *)downloadWithURL:(NSString *)url
//                                 savePathURL:(NSURL *)fileURL
//                                    progress:(LHProgress )progress
//                                     success:(void (^)(NSURLResponse *, NSURL *))success
//                                        fail:(void (^)(NSError *))fail{
//    AFHTTPSessionManager *manager = [self managerWithBaseURL:nil sessionConfiguration:YES];
//    
//    NSURL *urlpath = [NSURL URLWithString:url];
//    NSURLRequest *request = [NSURLRequest requestWithURL:urlpath];
//    
//    NSURLSessionDownloadTask *downloadtask = [manager downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
//        progress(downloadProgress);
//        
//    } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
//        
//        return [fileURL URLByAppendingPathComponent:[response suggestedFilename]];
//    } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
//        
//        if (error) {
//            fail(error);
//        }else{
//            
//            success(response,filePath);
//        }
//    }];
//    
//    [downloadtask resume];
//    
//    return downloadtask;
//}
//
//#pragma mark - Private
//
//+(AFHTTPSessionManager *)managerWithBaseURL:(NSString *)baseURL  sessionConfiguration:(BOOL)isconfiguration{
//    
//    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
//    AFHTTPSessionManager *manager =nil;
//    
//    NSURL *url = [NSURL URLWithString:baseURL];
//    
//    if (isconfiguration) {
//        
//        manager = [[AFHTTPSessionManager alloc] initWithBaseURL:url sessionConfiguration:configuration];
//    }else{
//        manager = [[AFHTTPSessionManager alloc] initWithBaseURL:url];
//    }
//    
//    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
//    manager.responseSerializer = [AFJSONResponseSerializer serializer];
//    
//    return manager;
//}
//
//+(id)responseConfiguration:(id)responseObject{
//    
//    NSString *string = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
//    string = [string stringByReplacingOccurrencesOfString:@"\n" withString:@""];
//    NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
//    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
//    return dic;
//}

+ (void)updateHeadImage:(UIImage *)headImage utl:(NSString *)url  andSuccessBlock:(sucessBlock)success andFaileBlock:(faileBlock)faile {
    NSData *data = UIImageJPEGRepresentation(headImage, 1.0);
    
    //获取uid
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSString *uid = [defaults objectForKey:@"uid"];
    NSString *mcode = [defaults objectForKey:@"mcode"];
    [defaults setObject:data forKey:@"mineHeadIcon"];
    [defaults synchronize];
    
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    manager.requestSerializer  = [AFHTTPRequestSerializer serializer];
    
    
    [manager POST:url parameters:@{@"uid":uid, @"mcode":mcode} constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        [formData appendPartWithFileData:data name:@"file" fileName:@"file.jpg" mimeType:@"image/jpeg"];
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        success(@"success");
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        faile(error);
    }];
    
}

+ (void)updateHeadImage:(NSArray *)headImages utl:(NSString *)url parameter:(NSMutableDictionary *)dic  andSuccessBlock:(sucessBlock)success andFaileBlock:(faileBlock)faile {
    
    //获取uid
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSString *uid = [defaults objectForKey:@"uid"];
    NSString *mcode = [defaults objectForKey:@"mcode"];


    [dic setObject:uid forKey:@"uid"];
    [dic setObject:mcode forKey:@"mcode"];
    
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    manager.requestSerializer  = [AFHTTPRequestSerializer serializer];
    
    
    [manager POST:url parameters:dic constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
        int i = 0;
        
        for (UIImage *image in headImages) {
            NSData *data = UIImageJPEGRepresentation(image, 0.2);
            [formData appendPartWithFileData:data name:[NSString stringWithFormat:@"img%d", i] fileName:[NSString stringWithFormat:@"img%d.jpg", i] mimeType:@"image/jpeg"];
            i++;
        }
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSDictionary *dic = [NSJSONSerialization  JSONObjectWithData:responseObject  options:NSJSONReadingMutableContainers error:nil ];
        
        success(dic);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        faile(error);
    }];
    
}

@end
